package com.senthink.gl.business.device.people;

import com.senthink.gl.business.common.entity.SearchRequest;
import com.senthink.gl.business.common.exception.BusinessException;
import com.senthink.gl.business.common.util.RandomUtils;
import com.senthink.gl.business.domain.entity.People;
import com.senthink.gl.business.domain.entity.PeopleEpi;
import com.senthink.gl.business.domain.entity.PeopleLive;
import com.senthink.gl.business.domain.repository.PeopleRepository;
import com.senthink.gl.business.domain.service.PeopleDataService;
import com.senthink.gl.business.fault.DeviceTypeEnum;
import com.senthink.gl.business.messages.CodeMsg;
import com.senthink.gl.business.response.ApiResponse;
import com.senthink.gl.business.response.CodeMsgDataResponse;
import com.senthink.gl.business.userlog.SystemUserLog;
import com.senthink.gl.business.userlog.enums.LogDetailEnum;
import com.senthink.gl.business.userlog.enums.LogOperateEnum;
import com.senthink.gl.business.userlog.enums.LogTypeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 民众
 *
 * @author zooqi@senthink.com
 * @date 2017/11/29
 */
@Service
public class PeopleService {

    @Autowired
    private CodeMsg codeMsg;
    @Autowired
    private PeopleDataService dataService;
    @Autowired
    private PeopleRepository peopleRepository;

    /**
     * 导出数据最大条数
     */
    @Value("${export.max}")
    private Integer maxExport;

    private static final Logger LOGGER = LoggerFactory.getLogger(PeopleService.class);

    /**
     * 添加
     *
     * @param request
     * @return
     */
    //@SystemUserLog(operate = LogOperateEnum.CREATE, detail = LogDetailEnum.CREATE_DEVICE, logType = LogTypeEnum.DEVICE, deviceType = DeviceTypeEnum.LAMP)
    public ApiResponse save(PeopleRequest request) {
        //判断是否存在
        if (dataService.countByIdcard(request.getIdcard()) != 0) {
            throw new BusinessException(codeMsg.snExistCode(), codeMsg.snExistMsg());
        }

        People people = new People();
        BeanUtils.copyProperties(request, people);
        people.setPid(RandomUtils.randomString(30));
        people.setLastModifiedTime(new Date());

         People people1 = dataService.save(people);

       //居住信息
        dataService.saveItems(convertToItems(request.getLives(),people1));
        //防疫信息

        PeopleEpi peopleEpi = new PeopleEpi();
        peopleEpi.setAddress(request.getEpi().getAddress());
        peopleEpi.setBackType(request.getEpi().getBackType());
        peopleEpi.setCheckLastTime(request.getEpi().getCheckLastTime());
        peopleEpi.setCheckStatus(request.getEpi().getCheckStatus());
        peopleEpi.setPeid(RandomUtils.randomString(30));
        peopleEpi.setCity(request.getEpi().getCity());
        peopleEpi.setStartTime(request.getEpi().getStartTime());
        peopleEpi.setPeople(people1);
        peopleEpi.setProvince(request.getEpi().getProvince());
        peopleEpi.setStatus(request.getEpi().getStatus());
        peopleEpi.setVaccination(request.getEpi().getVaccination());
        peopleEpi.setLastModifiedTime(new Date());
        dataService.saveEpi(peopleEpi);

        return new CodeMsgDataResponse<>(codeMsg.successCode(), codeMsg.successMsg());
    }

    private List<PeopleLive> convertToItems(Collection<PeopleLiveRequest> liveRequests,People people){
        List<PeopleLive> items = new LinkedList<>();
        for(PeopleLiveRequest peopleLiveRequest:liveRequests){
            PeopleLive item = new PeopleLive();
            item.setAddress(peopleLiveRequest.getAddress());
            item.setLastModifiedTime(new Date());
            item.setPeople(people);
            item.setPlid(RandomUtils.randomString(30));
            item.setSiteType(peopleLiveRequest.getSiteType());
            item.setRegion(peopleLiveRequest.getRegion());
            item.setVillage(peopleLiveRequest.getVillage());
            items.add(item);
        }
        return items;
    }

    /**
     * 获取灯具详情
     *
     * @param request
     * @return
     */
    public ApiResponse detail(PeopleRequest request) {
        People people = dataService.findTopByIdcard(request.getIdcard())
                .orElseThrow(() -> new BusinessException(codeMsg.recordNotFoundCode(), codeMsg.recordNotFoundMsg()));
        List<PeopleLive> peopleLives = dataService.findAllLiveByPeople(people);
        Optional<PeopleEpi> peopleEpiOptional = dataService.findTopByPeople(people);
        PeppleResponse response = new PeppleResponse();
        BeanUtils.copyProperties(people, response);
        response.setEpi(peopleEpiOptional.get());
        response.setLives(peopleLives);
        return new CodeMsgDataResponse(codeMsg.successCode(), codeMsg.successMsg(), response);
    }

    /**
     * 删除
     *
     * @param request
     * @return
     */
   // @SystemUserLog(operate = LogOperateEnum.DELETE, detail = LogDetailEnum.DELETE_DEVICE, logType = LogTypeEnum.DEVICE, deviceType = DeviceTypeEnum.LAMP)
    @Transactional(rollbackFor = Exception.class)
    public ApiResponse delete(PeopleRequest request) {
        People people = dataService.findByPid(request.getPid())
                .orElseThrow(() -> new BusinessException(codeMsg.recordNotFoundCode(), codeMsg.recordNotFoundMsg()));
       // onSnChanged(lamp.getSn());
        //居住信息
        dataService.deleteLive(people);
        //防疫信息
        dataService.deleteEpi(people);

        dataService.delete(people);
        return new CodeMsgDataResponse(codeMsg.successCode(), codeMsg.successMsg());
    }

    /**
     * 更新灯具信息
     *
     * @param request
     * @return
     */
    //@SystemUserLog(operate = LogOperateEnum.UPDATE, detail = LogDetailEnum.UPDATE_DEVICE, logType = LogTypeEnum.DEVICE, deviceType = DeviceTypeEnum.LAMP)
    @Transactional(rollbackFor = Exception.class)
    public ApiResponse update(PeopleRequest request) {
        People oldpeople = dataService.findByPid(request.getPid())
                .orElseThrow(() -> new BusinessException(codeMsg.recordNotFoundCode(), codeMsg.recordNotFoundMsg()));
        // 检查编号是否更改
        if (!oldpeople.getIdcard().equalsIgnoreCase(request.getIdcard())) {
            if (dataService.countByIdcard(request.getIdcard()) != 0) {
                throw new BusinessException(codeMsg.snExistCode(), codeMsg.snExistMsg());
            }
        }

        People people = new People();
        BeanUtils.copyProperties(oldpeople, people);
        BeanUtils.copyProperties(request, people);

        People people1 = dataService.save(people);

        dataService.deleteEpi(people);
        PeopleEpi peopleEpi = new PeopleEpi();
        peopleEpi.setAddress(request.getEpi().getAddress());
        peopleEpi.setBackType(request.getEpi().getBackType());
        peopleEpi.setCheckLastTime(request.getEpi().getCheckLastTime());
        peopleEpi.setCheckStatus(request.getEpi().getCheckStatus());
        peopleEpi.setPeid(RandomUtils.randomString(30));
        peopleEpi.setCity(request.getEpi().getCity());
        peopleEpi.setStartTime(request.getEpi().getStartTime());
        peopleEpi.setPeople(people1);
        peopleEpi.setProvince(request.getEpi().getProvince());
        peopleEpi.setStatus(request.getEpi().getStatus());
        peopleEpi.setVaccination(request.getEpi().getVaccination());
        peopleEpi.setLastModifiedTime(new Date());
        dataService.saveEpi(peopleEpi);

        dataService.deleteLive(people);
        dataService.saveItems(convertToItems(request.getLives(),people1));
        return new CodeMsgDataResponse<>(codeMsg.successCode(), codeMsg.successMsg());
    }

    /**
     * 分页+筛选+搜索灯具列表
     *
     * @param searchRequest 搜索参数
     * @param pageRequest   分页参数
     * @return
     */
    public ApiResponse peopleList(SearchRequest searchRequest, PageRequest pageRequest) {
        Page<People> page = dataService.findAll(searchRequest,  pageRequest);
        return new CodeMsgDataResponse<>(codeMsg.successCode(), codeMsg.successMsg(), page);
    }

}
